<?
class Url{
	static function build_all($except=array(), $addition=false){
		if(is_array($except))
			$except+=array('form_block_id','sbug','abug','tbug','delcache','delscache','utm_source','utm_campaign','utm_content','utm_medium');
		else
			$except=array('form_block_id','sbug','abug','tbug','delcache','delscache','utm_source','utm_campaign','utm_content','utm_medium');
		
		$url  = '';
		$page = '';
		
		foreach($_POST as $key=>$value){
			if(!in_array($key, $except) && $key!='form_block_id'){
				if(!is_array($value)){
					if($key=='page'){
						$page=urlencode($value);
					}
					else/*if($value!='')*/
						$url.=($url?'&':'').urlencode($key).'='.urlencode($value);
				}
			}
		}
		
		foreach($_GET as $key=>$value){	
			
			if(!in_array($key, $except) && $key!='form_block_id' && !isset($_POST[$key])){
				if($key=='page'){
					$page=urlencode($value);
				}
				else/*if($value!='')*/
                                    if(!is_array($value) && !is_array($key))
					$url.=($url?'&':'').urlencode($key).'='.urlencode($value);
                                    else {
                                        $temp = array();
                                        $meg = '';
                                        foreach($value as $v)
                                            $temp[] = $key.urlencode('[]').'='.$v;
                                        $meg = implode('&',$temp);
                                        $url.=($url?'&':'').$meg;
                                    }
			}
		}
		
		if($addition){
			$url.=($url?'&':'').$addition;
		}
		
		if(!$page || $page=='home'){
			$url=($url?'?':'').$url;
		}
		else{
			$url='?page='.$page.($url?'&'.$url:'');
		}
		
		//return $url?$url:'./';WEB_DIR
		//return $url?$url:WEB_ROOT;
		
		$url = ECRewrite::formatUrl($url);
		return $url?$url:WEB_DIR;
	}
	
	static function build_current($params=array(),$anchor=''){
		return Url::build((isset(ECore::$page['name'])?ECore::$page['name']:'home'),$params,$anchor);
	}
	
	static function build($page,$params=array(),$anchor=''){
		if($page=='home')
			$request_string = '';
		else{
			$request_string = '?page='.$page;
		}

		if ($params){
			foreach ($params as $param=>$value){
				if(is_numeric($param)){
					if(isset($_REQUEST[$value]) && $value!='page'){
						$request_string .= ($request_string?'&':'?').$value.'='.urlencode($_REQUEST[$value]);
					}
				}
				elseif($param!='page'){
					$request_string .= ($request_string?'&':'?').$param.'='.urlencode($value);
				}
			}
		}
		
		$request_string = ECRewrite::formatUrl($request_string);
		return WEB_DIR.$request_string.$anchor;
	}
	
	static function redirect_current($params=array(),$anchor = ''){
		Url::redirect(ECore::$page['name'],$params,$anchor);
	}
	
	static function redirect_href($params=false){
		if(Url::check('href')){
			Url::redirect_url(Url::attach($_REQUEST['href'],$params));
			return true;
		}
	}
	
	static function check($params){
		if(!is_array($params)){
			$params=array(0=>$params);
		}
		
		foreach($params as $param=>$value){
			if(is_numeric($param)){
				if(!isset($_REQUEST[$value])){
					return false;
				}
			}
			else{
				if(!isset($_REQUEST[$param])){
					return false;
				}
				else{
					if($_REQUEST[$param]!=$value){
						return false;
					}
				}
			}
		}
		return true;
	}
	
	//Chuyen sang trang chi ra voi $url
	static function redirect($page=false,$params=false, $anchor=''){
		if(!$page && !$params){
			Url::redirect_url();
		}
		else{
			Url::redirect_url(Url::build($page, $params,$anchor));
		}
	}
	
	static function redirect_url($url=false,$type = false){
		/*if(!$url || $url==''){
			$url='?'.$_SERVER['QUERY_STRING'];
		}*/
		
		if($url != ''){
			if(strpos($url,WEB_ROOT) === 0){
				$url = substr($url,strlen(WEB_ROOT));
			}
			if(strpos($url,WEB_DIR) === 0){
				$url = substr($url,strlen(WEB_DIR));
			}
			/*if (REWRITE_ON){
				$url= ECRewrite::doReplace($url);
				unset($rewrite);
			}*/
			$url = ECRewrite::formatUrl($url);
		}
		else{
			$url = '';
		}	
		
		
		if($type == 301){
			header("HTTP/1.1 301 Moved Permanently");
		}
		
		header('Location:'.WEB_DIR.$url);
		System::halt();
	}
	
    static function access_denied()
    {
        //TuanNK edit on 2012.12.18
        if(User::is_login())
        {
            Url::redirect();
        }
        else
        {
           ECLib::check_uri();

            Url::redirect('sign_in',array('href' => base64_encode(CGlobal::$query_string)));
        }
        //header("Location: ".WEB_ROOT."err/error.html");
        //die();
    }

	static function get($name,$default=''){
		/*if (isset($_REQUEST[$name])){
			return @trim($_REQUEST[$name]);
		}
		else*/
		if (isset($_POST[$name])){
			//return @trim($_POST[$name]);
			return $_POST[$name];
		}
		elseif(isset($_GET[$name])){
			return $_GET[$name];
		}
		else{
			return $default;		
		}
	}
	static function getInt($name,$default = 0){
		return (int)self::get($name,$default);
	}
	
	static function sget($name,$default=''){
		return strtr(Url::get($name, $default),array('"'=>'\\"'));
	}

    static function cdouble( $doubleval ){
	//echo $doubleval;
		//if(!is_numeric($doubleval))
		{			
			
			$doubleval=strtr($doubleval,array('.'=>''));
			$doubleval=strtr($doubleval,array(','=>'.'));
			
		}
		return doubleval($doubleval);
	}
	
	static function open_popup($url=false,$width=false,$height=false,$top=false,$left=false,$event=false,$resizable=0,$toolbar=0,$status=0,$scrollbars=0,$address_bar=0,$menubar=0){
		if(!$url)
			$url	='about:blank';
		elseif(strpos($url,'?')===false)
			$url.='?is_popup=1';
		else 
			$url.='&is_popup=1';
			
		if(!$width)
			$width	=300;
		if(!$height)
			$height	=400;
			
		if(!$top)
			$top	='\' + (screen.height -'.$height.')/2 +\'';		
		if(!$left)
			$left	='\' + (screen.width -'.$width.')/2 +\'';
		
		if(!$event)
			$event	='onclick';	

		return $event.'="window.open(\''.$url.'\' ,\'\',\'status='.$status.',toolbar='.$toolbar.',scrollbars='.$scrollbars.',resizable='.$resizable.',width='.$width.',height='.$height.',top='.$top.',left='.$left.',location ='.$address_bar.',menubar ='.$menubar.'\');"';	
	}
	
	
	//Hàm chuyển hướng trang tại chỗ
	static  function refresh($check_referer = 1)
	{
		if($check_referer && isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'])
		{
			$referer = $_REQUEST['HTTP_REFERER'];
		}
		else{
			$referer = $_SERVER['REQUEST_URI'];
		}
		
		Url::redirect_url($referer);
	}
	
	
    static function getParam($aVarName, $aVarAlt="")
    {
        $lVarName = trim(@$_REQUEST[$aVarName]);

        if (!Empty($lVarName)) {
            if (is_array($lVarName)) {
                $lReturnArray = array();
                foreach ($lVarName as $key => $value) {
                    $value = HTML::clean_value($value);
                    $key = HTML::clean_key($key);
                    $lReturnArray[$key] = $value;
                }
                return $lReturnArray;
            }
            else
                return HTML::clean_value($lVarName); // Clean input and return it




        }
        else
            return $aVarAlt;
    }

    static function getParamInt($aVarName, $aVarAlt=0) {
        $lNum = 0;
        if ($aVarName) {
            if (isset($_POST[$aVarName]))
                $lNum = $_POST[$aVarName];
            elseif (isset($_GET[$aVarName]))
                $lNum = $_GET[$aVarName];
            else
                $lNum = $aVarAlt;
        }

        return (int) trim($lNum);
        //return (int)preg_replace('/\D+/', '', $lNum);
    }

    static function getParamSearch($str_search) {
        $str_search = str_replace(array('+', '/', '|', '-', '*'), "", $str_search);
        $str_search = String::trimSpace($str_search);
        $str_search = str_replace("'", '"', $str_search);
        $str_search = str_replace("&#39;", '"', $str_search);
        $str_search = str_replace("&quot;", '"', $str_search);

        if (preg_match('"', $str_search)) {
            $pattern = '#\"(.+?)\"#is';
            preg_match_all($pattern, $str_search, $matches);
            $chars = preg_split($pattern, $str_search);

            $results = implode(" ", $matches[0]);
            foreach ($chars as $row) {
                if ($row) {
                    $row_array = explode(' ', $row);
                    if (is_array($row_array)) {
                        foreach ($row_array as $word) {
                            if ($word)
                                $results.=" +" . trim($word) . "";
                        }
                    }
                    else {
                        $results.=" +" . trim($row) . "";
                    }
                }
            }
            return $results;
        } else {
            $search_array = explode(' ', $str_search);
            $content = implode(" +", $search_array);
            $content = "+" . $content . '';
            return $content;
        }
    }
    
    /**
     * Hàm check các phần tử kiểu INT duy nhất trong chuỗi nhập vào dạng 1,2,3,4
     *
     * @param string $ids
     * @return string
     */
	function check_ids($ids , $sep = ",")
	{
		/*if($ids != '')
		{
			$ids = implode(',',array_unique(explode(',',$ids)));
		}
		
		return $ids;*/
		
		if($ids != '')
		{
			$arr  = array_unique(explode($sep,$ids));
			
			if($arr)
			{
				$arr2 = array();
				
				foreach ($arr as $id)
				{
					if($id != '' && $id > 0)
					{
						$arr2[(int)$id] = (int)$id;
					}
				}
				
				return  implode($sep,$arr2);
			}
		}
		
		return '';
	}
}
?>